layui.config({
    base: 'assets/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index', //主入口模块
}).use(['index', 'table', 'laytpl', 'laydate'], function(){
    var $ = layui.$,
        form = layui.form,
        table = layui.table,
        laydate = layui.laydate;

    var hostSearchData, curr = 1, limit = 50;
    var hostCommonData = JSON.parse(sessionStorage.getItem("hostCommonData"));
    sessionStorage.removeItem("hostCommonData");
    if(hostCommonData != null && !$.isEmptyObject(hostCommonData)){
        curr = hostCommonData.page;
        limit = hostCommonData.limit;
    }

    laydate.render({
        elem: '#time', //指定元素
        type: 'datetime',
        range: true
    });

    table.render({
        id: 'data-table',
        elem: '#data-table',
        url: 'host/list',
        where: getData(),
        toolbar: '#data-table-toolbar',
        title: '主播列表',
        height: globalHeight,
        page: true,
        limit: limit,
        cols: [[
            {field: 'userId', title: '主播id', width: 100, align: 'center'},
            {field: 'name', title: '昵称', align: 'center'},
            {field: 'phone', title: '手机', width: 120, align: 'center'},
            {field: 'icon', title: '头像', width: 80, align: 'center', templet: '#iconTpl'},
            {field: 'inviteCount', title: '邀请人数', width: 90, align: 'center', templet: '#inviteCountTpl'},
            {field: 'credit', title: '积分(可用/总数)', width: 150, align: 'center', templet: '#creditTpl'},
            {field: 'level', title: '等级', width:60, align: 'center'},
            {field: 'wi', title: '权重', width:60, align: 'center'},
            {field: 'identity', title: '会员', width: 60, align: 'center', templet: '#identityTpl'},
            {field: 'charge', title: '通话(金币/分钟)', width: 130, align: 'center'},
            {field: 'title', title: '头衔', width: 90, align: 'center', templet: '#titleTpl'},
            {field: 'online', title: '在线状态', width: 90, align: 'center', templet: '#onlineTpl'},
            {field: 'status', title: '账号状态', width: 90, align: 'center', templet: '#statusTpl'},
            {field: 'op', title: '操作', width: 300, align: 'center', templet: '#data-table-bar'}
        ]],
        parseData: function(result){
            return {
                "code": result.code, //解析接口状态
                "msg": result.msg, //解析提示文本
                "count": result.data.total, //解析数据长度
                "data": result.data.hosts //解析数据列表
            };
        },
        done: function (res, curr, count){
            var c = curr;
            if(c > 1){
                curr = 1;
                table.reload('data-table', {
                    page: {
                        curr : c
                    }
                });
            }
            if(hostSearchData != null && !$.isEmptyObject(hostSearchData)){
                reloadData(hostSearchData);
            }
        }
    });

    //头工具栏事件
    table.on('toolbar(data-table)', function(obj){
        switch(obj.event){
            case 'search':
                var data =  getData();
                table.reload('data-table', {
                    url: 'host/list',
                    where: data,
                    page: {
                        curr: 1
                    }
                });
                reloadData(data);
                break;
        };
    });

    //监听行工具事件
    table.on('tool(data-table)', function(obj){
        var data = obj.data;
        if(obj.event === 'updateLevel'){
            layer.open({
                type: 2,
                title: '设置主播等级/权重',
                offset: '25%',
                content: 'toUpdateLevel',
                area: ['550px', '250px'],
                btn: ['确定', '取消'],
                success: function(layero, index){   //弹窗成功后回调
                    var iframeWindow = window['layui-layer-iframe' + index];
                    $(iframeWindow.document).find('#id').val(data.id);   //传值到iframe页面
                    $(iframeWindow.document).find('#level').val(data.level);
                    $(iframeWindow.document).find('#wi').val(data.wi);
                },
                yes: function (index, layero) {     //确定按钮回调
                    var iframeWindow = window['layui-layer-iframe'+ index],
                        submit = layero.find('iframe').contents().find("#data-submit");

                    //监听提交
                    iframeWindow.layui.form.on('submit(data-submit)', function(data){
                        var field = data.field; //获取提交的字段
                        // 加载层
                        var load = layerLoad();
                        post('host/updateLevel', field, false, function (res) {
                            obj.update({
                                level: field.level,
                                wi: field.wi
                            });
                            layer.close(index); //关闭弹层
                            layer.close(load);
                            layer.msg("操作成功");
                        });
                    });

                    submit.trigger('click');
                },
            });

        }else if(obj.event === 'updateTitle'){
            var userId = data.userId;
            layer.open({
                type: 2,
                title: '设置主播头衔',
                offset: '25%',
                content: 'toUpdateTitle',
                area: ['400px', '300px'],
                btn: ['确定', '取消'],
                success: function(layero, index){   //弹窗成功后回调
                    var iframeWindow = window['layui-layer-iframe' + index];
                    $(iframeWindow.document).find('#id').val(data.userId);   //传值到iframe页面
                    $(iframeWindow.document).find('#title').val(data.title);
                },
                yes: function (index, layero) {     //确定按钮回调
                    var iframeWindow = window['layui-layer-iframe'+ index],
                        submit = layero.find('iframe').contents().find("#data-submit");

                    //监听提交
                    iframeWindow.layui.form.on('submit(data-submit)', function(data){
                        var field = data.field; //获取提交的字段
                        field.userId = userId;
                        // 加载层
                        var load = layerLoad();
                        post('host/updateTitle', field, false, function (res) {
                            obj.update({
                                title: field.title
                            });
                            layer.close(index); //关闭弹层
                            layer.close(load);
                            layer.msg("操作成功");
                        });
                    });

                    submit.trigger('click');
                },
            });

        }else if(obj.event === 'updateCall'){
            var msg;
            if(data.call == 0){
                msg = '确定禁止该用户视频通话权限吗？';
            }else{
                msg = '确定启用该用户视频通话权限吗？'
            }
            layer.confirm(msg, {offset: '30%'}, function(index){
                var call = data.call == 0 ? 1 : 0;
                // 加载层
                var load = layerLoad();
                post('user/updateCall', {id: data.userId, call: call}, false, function (res) {
                    obj.update({
                        call:  call,
                        op: 1
                    });
                    layer.close(index);
                    layer.close(load);
                    layer.msg('操作成功');
                });
            });
        }else if(obj.event === 'updateIM'){
            var msg;
            if(data.im == 0){
                msg = '确定禁止该用户IM权限吗？';
            }else{
                msg = '确定启用该用户IM权限吗？'
            }
            layer.confirm(msg, {offset: '30%'}, function(index){
                var im = data.im == 0 ? 1 : 0;
                // 加载层
                var load = layerLoad();
                post('user/updateIM', {id: data.userId, im: im}, false, function (res) {
                    obj.update({
                        im:  im,
                        op: 1
                    });
                    layer.close(index);
                    layer.close(load);
                    layer.msg('操作成功');
                });
            });
        }else if(obj.event === 'cancelAudit'){
            var msg = '确定取消该主播的认证吗？'
            layer.confirm(msg, {offset: '30%'}, function(index){
                // 加载层
                var load = layerLoad();
                post('host/cancelAudit', {userId: data.userId}, false, function (res) {
                    obj.del();
                    layer.close(index);
                    layer.close(load);
                    layer.msg('操作成功');
                });
            });
        }else if(obj.event === 'editImLimit'){
            layer.open({
                type: 2,
                title: '设置视频通话/im频率',
                offset: '15%',
                content: 'toEditImLimitManage',
                area: ['950px', '650px'],
                btn: ['确定', '取消'],
                success: function(layero, index){   //弹窗成功后回调
                    var iframeWindow = window['layui-layer-iframe' + index];
                    $(iframeWindow.document).find('#userId').val(data.userId);   //传值到iframe页面
                },
                yes: function (index, layero) {     //确定按钮回调
                    var iframeWindow = window['layui-layer-iframe'+ index],
                        submit = layero.find('iframe').contents().find("#data-submit");

                    //监听提交
                    iframeWindow.layui.form.on('submit(data-submit)', function(res){
                        var field = res.field; //获取提交的字段
                        // 加载层
                        var load = layerLoad();
                        post('user/editImLimit', field, false, function (resultData) {
                            layer.close(index); //关闭弹层
                            layer.close(load);
                            layer.msg("更新成功");
                        });
                    });

                    submit.trigger('click');
                }
            });

        }else if(obj.event === 'viewInvite'){
            hostSearchData = {'keyword': $('#keyword').val(), 'online': $('#online').val(), 'title': $('#title').val(), 'time': $('#time').val()};
            sessionStorage.setItem("hostSearchData", JSON.stringify(hostSearchData));
            sessionStorage.setItem("hostCommonData", JSON.stringify(getCommonData()));

            window.location.href = '/toInviteManage?hrefUrl=/toHostManage&inviteUserId=' + data.userId;

        }else if(obj.event === 'setClean'){
            layer.open({
                type: 2,
                title: '清退用户',
                offset: '25%',
                content: 'toSetCleanManage',
                area: ['500px', '300px'],
                btn: ['确定', '取消'],
                success: function(layero, index){   //弹窗成功后回调
                    var iframeWindow = window['layui-layer-iframe' + index];
                    $(iframeWindow.document).find('#userId').val(data.userId);   //传值到iframe页面
                },
                yes: function (index, layero) {     //确定按钮回调
                    var iframeWindow = window['layui-layer-iframe'+ index],
                        submit = layero.find('iframe').contents().find("#data-submit");

                    //监听提交
                    iframeWindow.layui.form.on('submit(data-submit)', function(data){
                        var field = data.field; //获取提交的字段
                        field.clean = 1;
                        // 加载层
                        var load = layerLoad();
                        post('user/setClean', field, false, function (resultData) {
                            obj.update({
                                clean:  1,
                                status: 1,
                                op: obj.data.op + 1
                            });
                            layer.close(index);
                            layer.close(load);
                            layer.msg("操作成功");
                        });
                    });

                    submit.trigger('click');
                }
            });

        }else if(obj.event === 'submitCleanWithdraw'){
            layer.open({
                type: 2,
                title: '提交清退提现申请',
                offset: '15%',
                content: 'toSubmitCleanWithdraw',
                area: ['950px', '650px'],
                btn: ['确定', '取消'],
                success: function(layero, index){   //弹窗成功后回调
                    var iframeWindow = window['layui-layer-iframe' + index];
                    $(iframeWindow.document).find('#userId').val(data.userId);   //传值到iframe页面
                    $(iframeWindow.document).find('#credit').val(data.credit);
                    var amount = parseInt(data.credit/data.moneyToCreditRate);
                    $(iframeWindow.document).find('#amount').val(amount);
                    $(iframeWindow.document).find('#alipayName').val(data.alipayName);
                    $(iframeWindow.document).find('#alipayNo').val(data.alipayNo);
                },
                yes: function (index, layero) {     //确定按钮回调
                    var iframeWindow = window['layui-layer-iframe'+ index],
                        submit = layero.find('iframe').contents().find("#data-submit");

                    //监听提交
                    iframeWindow.layui.form.on('submit(data-submit)', function(res){
                        var field = res.field; //获取提交的字段
                        // 加载层
                        var load = layerLoad();
                        post('user/submitCleanWithdraw', field, false, function (resultData) {
                            obj.update({
                                clean:  2,
                                status: 1,
                                credit: 0,
                                op: obj.data.op + 1
                            });
                            layer.close(index); //关闭弹层
                            layer.close(load);
                            layer.msg("更新成功");
                        });
                    });

                    submit.trigger('click');
                }
            });

        }


    });

    /**
     * 获取查询数据
     * @returns {{host: jQuery, online: jQuery, keyword: (*|jQuery|Array|string|undefined), status: (*|jQuery|Array|string|undefined)}}
     */
    function getData() {
        var keyword, online, title, time;
        hostSearchData = JSON.parse(sessionStorage.getItem("hostSearchData"));
        sessionStorage.removeItem("hostSearchData");
        if(hostSearchData != null && !$.isEmptyObject(hostSearchData)){
            keyword = hostSearchData.keyword;
            online = hostSearchData.online;
            title = hostSearchData.title;
            time = hostSearchData.time;
        }else{
            keyword = $('#keyword').val();
            online = $('#online').val();
            title = $('#title').val();
            time = $('#time').val();
        }

        return {'keyword': keyword, 'online': online, 'title': title, 'time': time};
    }

    /**
     * 重新渲染数据
     * @param data
     */
    function reloadData(data) {
        $('#keyword').val(data.keyword);
        $('#online').val(data.online);
        $('#title').val(data.title);
        $('#time').val(data.time);
        laydate.render({
            elem: '#time', //指定元素
            type: 'datetime',
            range: true
        });
        form.render();
    }
});